#!/usr/bin/env python
'''
DocIndexer MS Word parser.
Uses Antiword to extract text from Word documents.
'''
from abstract_parser import AbstractParser
from common import APP_DIR, EDocIndexer, short_path, shell_escape, encode_output
import os, string, tempfile

class Parser(AbstractParser):

    description = 'Antiword document parser'
    mime_types = ['application/antiword']

    def __init__(self):
        '''Check all parser resouces are available, throw error if not.'''
        if not self.isused():
            return
        if os.name == 'nt':
            dirname = os.path.abspath(os.path.join(APP_DIR,'antiword'))
            exe = os.path.join(dirname,'antiword.exe')
            if not os.path.isfile(exe):
                raise EDocIndexer, 'antiword required to build indexes'
            # The only way to set and pass environment variables to
            # popen() is to create a wrapper for popen() execution.
            self.script = os.path.join(tempfile.gettempdir(),'antiword.bat')
            f = file(self.script,'w+')
            f.write('@echo off\n')
            f.write('set ANTIWORDHOME=' + short_path(dirname) + '\n')
            f.write(short_path(exe) + ' %1\n')
            f.close()

    def text(self,filename):
        if os.name == 'nt':
            cmd = '"' + self.script + '" ' + short_path(filename)
        else:
            cmd = 'antiword "%s"' % shell_escape(filename)
            cmd = encode_output(cmd)    # popen() doesn't like unicode.
        try:
            f = os.popen(cmd)
            text = f.read()
            err = f.close()
            if err is not None:
                raise EDocIndexer,'non-zero Antiword exit status %d' % err
            if not string.strip(text):
                # KLUDGE: Because batch command exit codes are broken on Win9X.
                raise EDocIndexer,'Antiword unable to read document'
        except EDocIndexer:
            raise
        except:
            raise EDocIndexer,'unable to execute Antiword'
        return self.unicode(text)


if __name__ == '__main__':
    Parser.test()

# vim: set ts=4 sw=4:
